<template>
  <div>
    <!-- 连线题选项 -->
    <el-form-item v-if="question.type === '7'" label="选项">
      <div class="line-question-container">
        <div class="line-left-options">
          <div v-for="(item, index) in question.options.left" :key="'left'+index" class="line-option">
            <span class="option-index">{{ index + 1 }}.</span>
            <el-input :disabled="readonly" :value="item.content" @input="val => $set(item, 'content', val)" 
              placeholder="左侧选项" size="small" />
            <el-button v-if="!readonly" type="danger" icon="el-icon-delete" circle size="mini"
              @click="removeOption(index, 'left')" />
          </div>
        </div>
        <div class="line-right-options">
          <div v-for="(item, index) in question.options.right" :key="'right'+index" class="line-option">
            <span class="option-index">{{ index + 1 }}.</span>
            <el-input :disabled="readonly" :value="item.content" @input="val => $set(item, 'content', val)" 
              placeholder="右侧选项" size="small" />
            <el-button v-if="!readonly" type="danger" icon="el-icon-delete" circle size="mini"
              @click="removeOption(index, 'right')" />
          </div>
        </div>
        <el-button v-if="!readonly" type="primary" icon="el-icon-plus" circle size="mini"
          style="position: absolute; bottom: 10px; left: 50%; transform: translateX(-50%);"
          @click="addOption" />
      </div>
    </el-form-item>

    <!-- 单选题答案 -->
    <el-form-item v-if="question.type === '1'" label="答案">
      <el-radio-group :disabled="readonly" v-model="question.answer[0]" @change="$emit('answer-change')">
        <div v-for="item in question.select" :key="item.select">
          <el-radio :label="item.select">
            <el-select :disabled="readonly" v-model="item.select" style="width: 65px" size="small" placeholder>
              <el-option v-for="option in selectNotUse" :key="option" :label="option" :value="option" />
            </el-select>
            <myEdit :disabled="readonly" v-model="item.content" :inline="true" :use-dialog="true" size="small" />
            <el-link :disabled="readonly" :underline="false" icon="el-icon-error" type="danger"
              @click="removeItem(item)" />
          </el-radio>
        </div>
      </el-radio-group>
      <div v-if="!readonly">
        <el-link :underline="false" icon="el-icon-circle-plus" type="primary" @click="addItem" />
      </div>
    </el-form-item>

    <!-- 多选题答案 -->
    <el-form-item v-if="question.type === '2'" label="答案">
      <el-checkbox-group :disabled="readonly" v-model="question.answer" @change="$emit('answer-change')">
        <div v-for="item in question.select" :key="item.select">
          <el-checkbox :label="item.select">
            <el-select :disabled="readonly" v-model="item.select" style="width: 65px" size="small" placeholder>
              <el-option v-for="option in selectNotUse" :key="option" :label="option" :value="option" />
            </el-select>
            <myEdit :disabled="readonly" v-model="item.content" :inline="true" :use-dialog="true" size="small" />
            <el-link :disabled="readonly" :underline="false" icon="el-icon-error" type="danger"
              @click="removeItem(item)" />
          </el-checkbox>
        </div>
      </el-checkbox-group>
      <div v-if="!readonly">
        <el-link :underline="false" icon="el-icon-circle-plus" type="primary" @click="addItem" />
      </div>
    </el-form-item>

    <!-- 判断题答案 -->
    <el-form-item v-if="question.type === '3'" label="答案">
      <el-radio-group :disabled="readonly" v-model="question.answer[0]" @change="$emit('answer-change')">
        <div v-for="item in question.select" :key="item.select">
          <el-radio :label="item.select">
            <el-select :disabled="readonly" v-model="item.select" style="width: 65px" size="small" placeholder>
              <el-option v-for="option in selectNotUse" :key="option" :label="option" :value="option" />
            </el-select>
            <myEdit :disabled="readonly" v-model="item.content" :inline="true" :use-dialog="true" size="small" />
          </el-radio>
        </div>
      </el-radio-group>
    </el-form-item>

    <!-- 填空题答案 -->
    <el-form-item v-if="question.type === '4'" label="答案">
      <template v-for="index in question.blankSum">
        <el-input :key="index" :disabled="readonly" v-model="question.answer[index-1]" />
      </template>
    </el-form-item>

    <!-- 简答题答案 -->
    <el-form-item v-if="question.type === '5'" label="答案">
      <myEdit :disabled="readonly" v-model="question.answer[0]" />
    </el-form-item>

    <!-- 连线题答案 -->
    <el-form-item v-else-if="question.type === '7'" label="答案">
      <div class="line-question-container">
        <div class="line-connections">
          <div v-for="(item, index) in question.answer" :key="'conn'+index" class="line-connection">
            <span class="connection-index">{{ index + 1 }}.</span>
            <el-select :disabled="readonly" v-model="item.left" placeholder="左侧选项" size="small"
              @change="validateConnection(item.index)">
              <el-option v-for="(opt, idx) in question.options.left" :key="idx"
                :label="(idx + 1) + '. ' + opt.content" :value="idx + 1"
                :disabled="isLeftOptionUsed(idx + 1, item.index)" />
            </el-select>
            <span class="line-connection-arrow">→</span>
            <el-select :disabled="readonly" v-model="item.right" placeholder="右侧选项" size="small"
              @change="validateConnection(item.index)">
              <el-option v-for="(opt, idx) in question.options.right" :key="idx"
                :label="(idx + 1) + '. ' + opt.content" :value="idx + 1"
                :disabled="isRightOptionUsed(idx + 1, item.index)" />
            </el-select>
            <el-button v-if="!readonly" type="danger" icon="el-icon-delete" circle size="mini"
              @click="removeConnection(item.index)" />
          </div>
          <el-button v-if="!readonly" type="primary" icon="el-icon-plus" circle size="mini"
            @click="addConnection" />
        </div>
      </div>
    </el-form-item>

    <!-- 解析 -->
    <div v-if="['1', '2', '3', '4', '5', '7'].includes(question.type)">
      <el-form-item label="解析">
        <div style="display: flex; align-items: center;">
          <myEdit :disabled="readonly" v-model="question.analyze" style="flex: 1;" />
          <el-button v-if="!readonly" type="primary" size="small" style="margin-left: 10px;" 
            @click="$emit('ai-analyze')" :loading="aiAnalyzeLoading">AI解析</el-button>
        </div>
      </el-form-item>
    </div>
  </div>
</template>

<script>
import myEdit from "@/components/myEdit";

export default {
  name: "QuestionAnswer",
  components: {
    myEdit
  },
  props: {
    question: {
      type: Object,
      required: true
    },
    readonly: {
      type: Boolean,
      default: false
    },
    selectAnswer: {
      type: Array,
      default: () => ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
    },
    aiAnalyzeLoading: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    selectNotUse() {
      const arr = this.selectAnswer.filter((item) => {
        const x = this.question.select.find((s) => s.select === item);
        return !x;
      });
      return arr;
    }
  },
  methods: {
    addItem() {
      if (this.selectNotUse.length > 0) {
        this.question.select.push({
          select: this.selectNotUse[0],
          content: ""
        });
      }
    },
    removeItem(item) {
      const index = this.question.select.findIndex(s => s.select === item.select);
      if (index > -1) {
        this.question.select.splice(index, 1);
      }
    },
    addOption() {
      if (!this.question.options) {
        this.question.options = {
          left: [],
          right: []
        };
      }
      const leftIndex = this.question.options.left.length + 1;
      const rightIndex = this.question.options.right.length + 1;
      this.question.options.left.push({ content: '', index: leftIndex });
      this.question.options.right.push({ content: '', index: rightIndex });
    },
    removeOption(index, side) {
      this.question.options[side].splice(index, 1);
      this.question.options[side].forEach((option, idx) => {
        option.index = idx + 1;
      });
      if (side === 'left') {
        this.question.answer = this.question.answer.filter(conn => conn.left !== index + 1);
        this.question.answer.forEach(conn => {
          if (conn.left > index + 1) conn.left--;
        });
      } else {
        this.question.answer = this.question.answer.filter(conn => conn.right !== index + 1);
        this.question.answer.forEach(conn => {
          if (conn.right > index + 1) conn.right--;
        });
      }
    },
    addConnection() {
      if (!this.question.answer) {
        this.$set(this.question, 'answer', []);
      }
      const newConnection = { left: undefined, right: undefined, index: this.question.answer.length };
      this.$set(this.question.answer, this.question.answer.length, newConnection);
    },
    removeConnection(index) {
      this.question.answer.splice(index, 1);
      this.question.answer.forEach((conn, idx) => {
        this.$set(conn, 'index', idx);
      });
    },
    isLeftOptionUsed(leftIndex, currentConnectionIndex) {
      return this.question.answer.some((conn, idx) =>
        idx !== currentConnectionIndex && conn.left === leftIndex
      );
    },
    isRightOptionUsed(rightIndex, currentConnectionIndex) {
      return this.question.answer.some((conn, idx) =>
        idx !== currentConnectionIndex && conn.right === rightIndex
      );
    },
    validateConnection(index) {
      const connection = this.question.answer[index];
      if (connection.left !== undefined && connection.right !== undefined) {
        const leftDuplicate = this.question.answer.some((conn, idx) =>
          idx !== index && conn.left === connection.left
        );
        const rightDuplicate = this.question.answer.some((conn, idx) =>
          idx !== index && conn.right === connection.right
        );

        if (leftDuplicate || rightDuplicate) {
          if (leftDuplicate) this.$set(connection, 'left', undefined);
          if (rightDuplicate) this.$set(connection, 'right', undefined);
        }
      }
    }
  }
};
</script>

<style scoped>
.line-question-container {
  display: flex;
  justify-content: space-between;
  margin: 20px 0;
  position: relative;
}

.line-left-options,
.line-right-options {
  width: 45%;
  padding: 15px;
  border: 2px dashed #dcdfe6;
  border-radius: 4px;
  min-height: 200px;
}

.line-option {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.line-option .el-input {
  margin-right: 10px;
  flex: 1;
}

.option-index {
  margin-right: 8px;
  font-weight: bold;
}

.connection-index {
  margin-right: 8px;
  font-weight: bold;
}

.line-connection {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.line-connection-arrow {
  margin: 0 10px;
  font-weight: bold;
  color: #409EFF;
}

.line-connections {
  width: 100%;
}
</style>